<template>
    <div class="container">
        <div class="address">
            <div style="font-weight: bold; font-size: 1.2rem; margin-bottom: 1rem">选择收货地址</div>
            <el-table
                :data="addressList"
                highlight-current-row
                ref="addressTable"
                @current-change="selectAddress"
                style="width: 90%; margin: 0 auto"
            >
                <template #empty>
                    <div>啥也没有呢</div>
                    <el-button type="primary" @click="showAddForm = true">添加第一条地址</el-button>
                </template>
                <el-table-column type="index" width="50"></el-table-column>
                <el-table-column prop="name" label="收货人姓名" width="100"></el-table-column>
                <el-table-column prop="region" label="地区" width="160"></el-table-column>
                <el-table-column prop="detail" label="详细地址"></el-table-column>
                <el-table-column prop="code" label="邮政编码" width="80"></el-table-column>
                <el-table-column prop="telephone" label="手机号码" width="120"></el-table-column>
                <el-table-column prop="status" label="默认地址" width="120">
                    <template #default="scope">
                        <el-tag v-if="scope.row.status === 1" type="danger" style="margin-left: 10px">默认地址</el-tag>
                        <el-button type="text" v-else @click="setDefault(scope.row)" size="small"
                            >设为默认地址</el-button
                        >
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div class="order">
            <div style="font-weight: bold; font-size: 1.2rem; margin-bottom: 1rem; margin-top: 2rem">确认订单信息</div>
            <el-table
                :data="orderList"
                v-loading="isLoading"
                @selection-change="selectionChange"
                @select-all="selectAll"
                ref="table"
            >
                <el-table-column type="index" label="序号" width="60" />
                <el-table-column prop="coverImg" label="图片">
                    <template #default="scope">
                        <el-image :src="scope.row.coverImg" style="width: 80px"></el-image>
                    </template>
                </el-table-column>
                <el-table-column prop="title" label="书名"></el-table-column>
                <el-table-column prop="author" label="作者"></el-table-column>
                <el-table-column label="单价">
                    <template #default="scope">
                        <span>{{ scope.row.price.toFixed(2) }}元</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template #default="scope">
                        <el-button type="text" @click="currentDelete(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div class="footer">
            <el-button type="danger" @click="confirmHandler">提交订单</el-button>
        </div>
        <el-dialog v-model="showAddForm">
            <AddressForm  />
        </el-dialog>
    </div>
</template>

<script>
import store from "@/store";
import service from "@/utils/request";
import { ElMessage, ElMessageBox } from "element-plus";
import AddressForm from "@/components/Address/AddressForm.vue";

export default {
    components: { AddressForm },
    data() {
        return {
            bookID: 0,
            addressInfo: [],
            userID: store.state.userInfo.userID,
            isLoading: true,
            addressList: [],
            selectedAddress: null,
            defaultAddress: null,
            orderList: [],
            showAddForm: false,
        };
    },
    computed: {},
    methods: {
        refresh() {
            // 获取地址信息
            service({
                method: "get",
                url: `/address/selectByUserId/${this.userID}`,
                headers: {
                    token: store.state.token,
                },
            }).then((res) => {
                // console.log(res.data);
                this.addressList = res.data;
                this.defaultAddress = this.addressList.filter((item) => item.status === 1);
                // this.$refs["addressTable"].setCurrentRow(this.addressList.filter((item) => item.status === 1));
            });

            // 获取订单信息
            service({
                method: "get",
                url: `/order/selectById/${this.userID}?orderState=2&payState=0`,
            }).then((res) => {
                // console.log(res.data);
                res.data.forEach((item) => {
                    Object.assign(item, ...item.book, item);
                    delete item["book"];
                    // console.log(item);
                });
                this.orderList = res.data;
            });
        },
        selectAddress(row) {
            this.selectedAddress = row;
        },
        setDefault(row) {
            // console.log(row);
            service
                .post(`/address/setDefault/${row.addressID}/${this.userID}`)
                .then(() => {
                    ElMessage({
                        type: "success",
                        message: "设为默认地址成功",
                    });
                    this.refresh();
                })
                .catch((err) => {
                    console.log(err);
                });
        },
        currentDelete(row) {
            // console.log(row.orderID);
            service({
                method: "get",
                url: `/order/delete?id=${row.orderID}`,
                headers: {
                    token: store.state.token,
                },
            }).then((res) => {
                console.log(res);
                this.refresh();
            });
        },
        confirmHandler() {
            let address = this.selectedAddress === null ? this.defaultAddress : this.selectedAddress;
            let orderAddress = address.region.toString() + address.detail.toString();
            // console.log(address.name, address.telephone);
            // console.log(orderAddress);
            this.orderList.forEach((item) => {
                // console.log(item);
                service({
                    method: "post",
                    url: "/order/update",
                    headers: {
                        token: store.state.token,
                        "Content-type": "application/json",
                    },
                    data: {
                        orderID: item.orderID,
                        userID: item.userID,
                        name: address.name,
                        bookID: item.bookID,
                        telephone: address.telephone,
                        orderAddress,
                        orderState: 2,
                        payState: 0,
                    },
                })
                    .then((res) => {
                        console.log(res);
                    })
                    .catch((err) => {
                        console.log(err);
                    });
            });
            ElMessageBox.confirm("提交订单成功，要马上付款吗？", "提示", {
                type: "success",
                confirmButtonText: "付款",
                cancelButtonText: "暂时不付",
            })
                .then(() => {
                    this.orderList.forEach(async (item) => {
                        await service({
                            method: "post",
                            url: `/order/update`,
                            data: {
                                orderID: item.orderID,
                                userID: item.userID,
                                name: address.name,
                                bookID: item.bookID,
                                telephone: address.telephone,
                                orderAddress,
                                orderState: 2,
                                payState: 1,
                            },
                        }).then((res) => {
                            // console.log(res);
                            ElMessage({
                                type: "success",
                                message: "付款成功",
                            });
                        });
                        this.$router.replace({ name: "order" });
                    });
                })
                .catch(() => {
                    this.$router.replace({ name: "order" });
                });
        },
    },
    async beforeMount() {
        this.bookID = this.$route.params.bookID;
        this.isLoading = true;
        await this.refresh();
        this.isLoading = false;
    },
    async mounted() {
        await service({
            method: "get",
            url: `/address/getDefault/${this.userID}`,
            headers: {
                token: store.state.token,
            },
        }).then((res) => {
            // console.log(res.data);
            this.defaultAddress = res.data;
            // console.log(this.defaultAddress);
        });
    },
};
</script>
<style lang="scss" scoped>
.container {
    width: 90%;
    margin: 0 auto;

    .address {
        padding: 1rem;
        border: 1px solid var(--el-border-color-light);
    }

    .order {
        padding: 1rem;
        margin-bottom: 2rem;
    }

    .footer {
        text-align: right;
    }
}
</style>
